package cn.wzvtcsoft.common.util;

import cn.wzvtcsoft.common.vo.PageVo;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;


/**
 * @author Exrickx
 */
public class PageUtil {

    public static Pageable initPage(PageVo page) {

        Pageable pageable = null;
        int pageNumber = page != null ? page.getPageNumber() : 1;
        int pageSize = page != null ? page.getPageSize() : 10;
        String sort = page != null ? page.getSort() : null;
        String order = page != null ? page.getOrder() : null;

        /*if(pageNumber<1){
            pageNumber=1;
        }
        if(pageSize<1){
            pageSize=10;
        }*/
        if (!StringUtils.isEmpty(sort)) {
            Sort.Direction d;
            if (StringUtils.isEmpty(order)) {
                d = Sort.Direction.DESC;
            } else {
                d = Sort.Direction.valueOf(order.toUpperCase());
            }
            Sort s = new Sort(d, sort);
            pageable = PageRequest.of(pageNumber - 1, pageSize, s);
        } else {
            pageable = PageRequest.of(pageNumber - 1, pageSize);
        }
        return pageable;
    }
}
